package multithread;

//CountDownLatch

import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class ThreadDemo19 {
    public static void main(String[] args) throws InterruptedException {
        //1.CountDownLatch 用来感知是否所有线程都执行完毕
        //参数为 任务的个数
        CountDownLatch latch = new CountDownLatch(10);
        //创建出10个线程进行下载：
        for (int i = 0; i < 10; i++) {
            int id = i;
            Thread t = new Thread(()->{
                Random random=new Random();
                //[ 0 , 5 )
                int time = (random.nextInt(5)+1);
                System.out.println("Thread NO." + id + "开始下载");
                try {
                    Thread.sleep(time);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("Thread NO." + id + "结束下载");
                //2.CountDown():告知任务执行结束
                latch.countDown();
            });
            t.start();
        }
        //3.await():统一进行等待所有任务结束 即 CountDown被调用10次
        latch.await();
        System.out.println("所有任务都执行完毕");
    }
}



